<template>
  <div class="app-container">
    <ViewSessions
      class="sousuo"
      style="margin-bottom: 15px"
      @selected="selected"
      @add="add"
    />
    <el-table
      border
      :row-class-name="tableRowClassName"
      :data="orderList"
      :header-row-style="{
        'background-color': '#E6E6E6',
        'font-weight': 'bold',
        color: '#333'
      }"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      height="650"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
    >
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="orderCode"
        label="内部订单编号"
        width="160px"
      />

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="picCode"
        label="图号"
        width="180px"
      />

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="picName"
        label="名称"
      />

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="amount"
        label="数量"
      />
      <!-- <el-table-column show-overflow-tooltip align="center" prop="processName" label="工序名称/描述"/>
      <el-table-column show-overflow-tooltip align="center" prop="isAssist" label="外协否">
        <template slot-scope="scope">
          <span>{{ scope.row.isAssist == 1 ? '否' : '是' }}</span>
        </template>
      </el-table-column> -->

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="isAssist"
        label="是否到货"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.isArrive===1 ? "是" : "否" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="deliveryTime"
        label="交货日期"
      />

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="examiner"
        label="检验员"
      />

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="engineerName"
        label="工程师"
      />
      <el-table-column
        v-if="hasRole()"
        show-overflow-tooltip
        align="center"
        prop="unitPrice"
        label="单价"
      />
      <el-table-column
        v-if="hasRole()"
        show-overflow-tooltip
        align="center"
        prop="totalPrice"
        label="总价"
      />
      <!-- <el-table-column show-overflow-tooltip align="center" prop="examine" label="检验结果"/> -->
      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="alignTime"
        label="标准工时"
      /> -->
      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="actualTime"
        label="实际工时"
      /> -->
      <el-table-column
        show-overflow-tooltip
        align="center"
        label="状态"
        prop="statusName"
      />
      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="deleteRemark"
        label="备注"
      /> -->
      <el-table-column fixed="right" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="() => dispatchOpen(scope.row)"
          >派单
          </el-button>

          <el-button
            :disabled="!scope.row.productId"
            type="text"
            size="mini"
            @click="() => arrangeDetail(scope.row.productId)"
          >详情
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="seePaper(scope.row)"
          >查看图纸</el-button
          >
          <!-- <el-button
            type="text"
            size="mini"
            @click="() => upload(scope.row)"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.deleteFlag == 1"
            type="text"
            size="mini"
            @click="() => seeDeleteItem(scope.row)"
          >查看
          </el-button>
          <el-button
            v-if="scope.row.deleteFlag != 1"
            type="text"
            size="mini"
            @click="() => delect(scope.row)"
          >删除
          </el-button>
           -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: end"
      layout="total, prev, pager, next,jumper"
      @current-change="fetchData"
    />
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogFormValue"
      @close="closeDialog"
    >
      <el-form
        ref="order"
        :model="order"
        :rules="validateRules"
        label-width="120px"
      >
        <el-form-item label="订单编号：" prop="orderCode">
          <el-col :span="8">
            <el-select
              :disabled="readonlyInput"
              v-model="order.orderCode"
              clearable
              placeholder="请选择订单"
            >
              <el-option
                v-for="item in orderNoList"
                :key="item.insideCode"
                :label="item.insideCode"
                :value="item.insideCode"
              />
            </el-select>
            <!-- <el-input
              size="small"
              v-model="order.productId"
              placeholder="请输入产品编号"
            /> -->
          </el-col>
        </el-form-item>
        <el-form-item label="项次：" prop="item">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.item"
              size="small"
              placeholder="请输入项次"
            />
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="工序：" prop="process">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.process"
              size="small"
              placeholder="请输入工序"
            />
          </el-col>
        </el-form-item> -->
        <!-- <el-form-item label="工序名称：" prop="processName">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.processName"
              size="small"
              placeholder="请输入工序名称"
            />
          </el-col>
        </el-form-item> -->
        <!-- <el-form-item label="外协否：" prop="isAssist">
          <el-col :span="8">
            <el-select
              :disabled="readonlyInput"
              v-model="order.isAssist"
              clearable
              placeholder="请选择是否外协"
              @change="changeAssist"
            >
              <el-option
                v-for="item in isAssistList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-form-item> -->
        <div v-if="order.isAssist == 0">
          <el-form-item label="外协费用：" prop="cost">
            <el-col :span="8">
              <el-input
                :disabled="readonlyInput"
                v-model="order.cost"
                size="small"
                placeholder="请输入费用"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="外协负责人：" prop="officeUserName">
            <el-col :span="8">
              <el-input
                :disabled="readonlyInput"
                v-model="order.officeUserName"
                size="small"
                placeholder="请输入外协负责人"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="外协外部联系人：" prop="outConnectName">
            <el-col :span="8">
              <el-input
                :disabled="readonlyInput"
                v-model="order.outConnectName"
                size="small"
                placeholder="请输入外协外部联系人"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="外协外部联系人电话：" prop="outConnectPhone">
            <el-col :span="8">
              <el-input
                :disabled="readonlyInput"
                v-model="order.outConnectPhone"
                size="small"
                placeholder="请输入外协外部联系人电话"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="外出时间：" prop="outStartTime">
            <el-col :span="6">
              <el-date-picker
                :disabled="readonlyInput"
                v-model="order.outStartTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择外出时间："
              />
            </el-col>
          </el-form-item>
          <el-form-item label="归来时间：" prop="outEndTime">
            <el-col :span="6">
              <el-date-picker
                :disabled="readonlyInput"
                v-model="order.outEndTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择归来时间："
              />
            </el-col>
          </el-form-item>
          <el-form-item label="备注：">
            <el-col :span="8">
              <el-input
                :disabled="readonlyInput"
                v-model="order.remark"
                size="small"
                placeholder="请输入备注"
              />
            </el-col>
          </el-form-item>
        </div>

        <el-form-item label="操作者：" prop="operaterName">
          <!-- <el-col :span="8">
            <el-input
              v-model="order.operaterName"
              size="small"
              placeholder="请输入操作者"
            />
          </el-col> -->
          <el-col :span="8">
            <el-select
              :disabled="readonlyInput"
              v-model="order.userId"
              clearable
              placeholder="请选择操作者"
              @change="changeoperater"
            >
              <el-option
                v-for="item in operaterNameList"
                :key="item.id"
                :label="item.fullName"
                :value="item.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="数量：" prop="amount">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.amount"
              size="small"
              placeholder="请输入数量"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="设备：" prop="equipment">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.equipment"
              size="small"
              placeholder="请输入设备"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="标准工时：" prop="equipment">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.alignTime"
              size="small"
              placeholder="请输入标准工时"
            />
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restData()">取 消</el-button>
        <el-button type="primary" @click="append('order')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogDelect">
      <el-input
        :rows="2"
        v-model="textDelect"
        type="textarea"
        placeholder="请输入删除理由"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="delectClick">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :visible.sync="detailModal.show" title="详情">
      <div v-loading="detailModal.loading" class="the-detail-dialog-content">
        <el-descriptions
          v-for="(detail, index) in detailModal.list"
          :title="getStepText(detail.step)"
          :key="index"
          :column="1"
        >
          <el-descriptions-item label="工艺名称">{{
            detail.craft
          }}</el-descriptions-item>
          <el-descriptions-item label="组长">{{
            detail.chargemanName
          }}</el-descriptions-item>
          <el-descriptions-item label="操作工1">{{
            detail.userName1
          }}</el-descriptions-item>
          <el-descriptions-item label="操作者1作业时间">{{
            detail.userId1Time
          }} - {{ detail.userId1FinishTime }}</el-descriptions-item>
          <el-descriptions-item label="操作工2">{{
            detail.userName2
          }}</el-descriptions-item>
          <el-descriptions-item label="操作者2作业时间">{{
            detail.userId2Time
          }} - {{ detail.userId2FinishTime }}</el-descriptions-item>
          <el-descriptions-item label="操作工3">{{
            detail.userName3
          }}</el-descriptions-item>
          <el-descriptions-item label="操作者3作业时间">{{
            detail.userId3Time
          }} - {{ detail.userId3FinishTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            statusMap[detail.status]
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="pdfUrlShow"
      title="图纸路径"
      @close="pdfUrlShow = false"
    >
      <el-form label-width="120px">
        <el-form-item label="图纸路径：">
          <div>
            <el-button
              v-for="(url, index) in pdfUrl"
              :key="index"
              style="text-align: left;"
              type="text"
            >
              <a
                :href="url"
                style="white-space: initial; word-break: break-all; word-wrap: break-word;"
                target="_blank"
              >{{ url }}</a
              >
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="工艺：">
          <div v-for="(item, index) in artFiles" :key="index">
            <a
              :href="item"
              style="
								color: #409eff;
								border-bottom: #409eff 1px solid;
							"
              target="_blank"
            >{{ item }}</a
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogDispatchFormVisible"
      title="制定派单人员"
    >
      <el-form
        ref="dispatch"
        :model="dispatch"
        label-width="300px"
      >
        <el-form-item label="请选择派单人员：" prop="code">
          <el-select v-model="dispatch.userId" clearable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.fullName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restDispatchData()">取 消</el-button>
        <el-button type="primary" @click="saveDispatch()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ViewSessions from './ViewSessions.vue'
import user from '../../api/acl/user.js'
import { toChineseText } from '@/utils/index.js'
import ElDescriptions from '../engineering/el-descriptions.vue'
import ElDescriptionsItem from '../engineering/el-descriptions-item.vue'

export default {
  components: {
    ViewSessions,
    ElDescriptions,
    ElDescriptionsItem
  },
  data() {
    return {
      statusMapTab: {
        1: '未开始',
        21: '已派单',
        22: '已外协',
        23: '已派单-已外协',
        24: '外协已完成/已到货',
        3: '生产中',
        4: '待品检',
        41: '报废',
        42: '可维修',
        43: '合格',
        44: '不合格',
        5: '品检中',
        51: '待入库',
        6: '入库中',
        7: '出库中',
        8: '已完成'
      },
      statusMap: {
        0: '未开始',
        1: '已开始',
        2: '已完成'
      },
      orderNoList: [],
      readonlyInput: false,
      operaterNameList: [],
      dialogDelect: false,
      textDelect: '',
      productList: [],
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      validateRules: {
        orderCode: [
          { required: true, trigger: 'change', message: '请选择订单' }
        ],
        productId: [
          { required: true, trigger: 'change', message: '请选择产品' }
        ],
        item: [{ required: true, trigger: 'change', message: '请输入项次' }],
        process: [{ required: true, trigger: 'change', message: '请输入工序' }],
        processName: [
          { required: true, trigger: 'change', message: '请选择工序名称' }
        ],
        isAssist: [
          { required: true, trigger: 'change', message: '请选择是否外协' }
        ]
      },
      orderList: [],
      dialogFormVisible: false,
      dialogFormValue: '',
      processList: [
        {
          value: '0',
          label: '数控立车'
        },
        {
          value: '1',
          label: '数控离子'
        }
      ],
      isAssistList: [
        {
          value: '0',
          label: '是'
        },
        {
          value: '1',
          label: '否'
        }
      ],
      order: {
        orderCode: '',
        alignTime: '',
        productId: '',
        item: '',
        processName: '',
        process: '',
        isAssist: '1',
        amount: '',
        operaterName: '',
        equipment: '',
        id: '',
        officeUserName: '',
        cost: '',
        outConnectName: '',
        outConnectPhone: '',
        outStartTime: '',
        outEndTime: '',
        remark: '',
        userId: ''
      },
      pdfUrl: '',
      pdfUrlShow: false,
      artFiles: [],
      searchInfo: {
        orderCode: '',
        picCode: '',
        picName: '',
        status: '',
        isDelivery: ''
        // item: '',
        // process: ''
      },
      detailModal: {
        show: false,
        loading: false,
        productId: '',
        list: []
      },
      dialogDispatchFormVisible:false,
      dispatch:{
        id:null,
        userId:null
      },
      dispatchUser:{
        department:14,
        page:1,
        limit:100000
      },
      options:[]
    }
  },
  // 监听上面文本框搜索
  watch: {},

  created() {},
  mounted() {
    this.searchInfo.productId = this.$route.query.id
      ? this.$route.query.id
      : ''
    this.listProductItem()
    this.listAllProduct()
    this.listUser()
    this.listAllOrder()
  },
  methods: {
    dispatchOpen(val){
      this.dialogDispatchFormVisible = true
      this.dispatch.id = val.productId
      this.dispatch.userId = null
      user.getDispatchUser(this.dispatchUser).then((response) => {
        this.options = response.list
      })
    },
    restDispatchData(){
      this.dialogDispatchFormVisible = false
    },
    saveDispatch(){
      if (this.dispatch.userId == null){
        this.$message.error('请制定派遣人员')
      }
      user.saveDispatch(this.dispatch).then((response) => {
        this.$message.success('派单成功')
        this.dialogDispatchFormVisible = false
        this.listProductItem()
      })
    },
    hasRole: function() {
      return window.sessionStorage.getItem("department") === '7' || window.sessionStorage.getItem("userName") ==='admin';
    },
    changeAssist(val) {
      console.log(val)
      this.order.officeUserName = ''
      this.order.cost = ''
      this.order.outConnectName = ''
      this.order.outConnectPhone = ''
      this.order.outStartTime = ''
      this.order.outEndTime = ''
      this.order.remark = ''
    },
    listAllOrder() {
      user.listAllOrder().then(response => {
        this.orderNoList = response
      })
    },
    changeoperater(data) {
      console.log(data)
      this.operaterNameList.forEach(val => {
        if (val.id == data) {
          this.order.operaterName = val.fullName
        }
      })
    },
    listUser() {
      user
        .listUser({
          department: '6',
          limit: 1000,
          page: 1
        })
        .then(response => {
          this.operaterNameList = response.list
        })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.deleteFlag == 1) {
        return 'warning-row'
      }
      return ''
    },
    delectClick() {
      if (this.textDelect == '') {
        this.$message({
          message: '请输入删除理由',
          duration: 1000
        })
        return
      }
      user
        .deleteProductItem({
          deleteFlag: 1,
          id: this.delectId,
          deleteRemark: this.textDelect
        })
        .then(response => {
          this.delectId = ''
          this.textDelect = ''
          this.dialogDelect = false
          this.$message({
            message: '删除成功',
            duration: 1000
          })
          this.listProductItem()
        })
    },
    delect(val) {
      this.delectId = val.id
      this.textDelect = ''
      this.dialogDelect = true
    },
    listAllProduct() {
      user.listAllProduct().then(response => {
        console.log(response)
        this.productList = response
      })
    },
    fetchData(val) {
      this.page = val
      this.listProductItem()
    },
    getStepText(index) {
      return '步骤' + toChineseText(index)
    },
    seePaper(row) {
      user.listImageFolder(row).then(response => {
        if (response && response.imageUrl) {
          this.pdfUrl =
            typeof response.imageUrl === 'string'
              ? [response.imageUrl]
              : response.imageUrl || []
          this.pdfUrlShow = true
          this.artFiles = response.artFiles
        } else {
          this.$message.info('暂无图纸信息')
        }
      })
    },
    // 查看详情
    arrangeDetail(productId) {
      this.detailModal.productId = productId
      this.detailModal.show = true
      this.detailModal.loading = true
      this.listCheckDetail(productId).then(list => {
        this.detailModal.list = list || []
        this.detailModal.loading = false
      })
    },
    // 获取详情接口
    listCheckDetail(productId) {
      return new Promise((resolve, reject) => {
        user
          .listCheckDetail({
            productId
          })
          .then(list => {
            resolve(list)
          })
          .catch(() => {
            this.detailModal.loading = false
          })
      })
    },
    listProductItem() {
      user
        .listProductItem({
          ...this.searchInfo,
          limit: this.limit,
          page: this.page,
          status: this.searchInfo.status
          // item: this.searchInfo.item,
          // process: this.searchInfo.process
        })
        .then(response => {
          this.total = response.total
          this.orderList =
            response.list.map(item => {
              item.statusName = this.statusMapTab[item.status || ''] || '--'
              return item
            }) || []
          // this.orderList = response.list
        })
    },
    closeDialog() {
      this.order = {
        orderCode: '',
        alignTime: '',
        productId: '',
        item: '',
        processName: '',
        process: '',
        isAssist: '1',
        amount: '',
        operaterName: '',
        userId: '',
        equipment: '',
        id: '',
        officeUserName: '',
        cost: '',
        outConnectName: '',
        outConnectPhone: '',
        outStartTime: '',
        outEndTime: '',
        remark: ''
      }
      this.$refs.order.resetFields()
    },
    append(val) {
      console.log(this.order)
      this.$refs[val].validate(valid => {
        if (valid) {
          if (this.order.id == '') {
            // 新增
            user
              .insertProductItem({
                orderCode: this.order.orderCode, // 订单编号
                alignTime: this.order.alignTime,
                productCode: this.order.productId,
                item: this.order.item,
                processName: this.order.processName,
                process: this.order.process,
                isAssist: this.order.isAssist,
                amount: this.order.amount,
                userId: this.order.userId,
                operaterName: this.order.operaterName,
                equipment: this.order.equipment,
                productItemAssist: {
                  // productId: this.order.productId,
                  officeUserName: this.order.officeUserName,
                  cost: this.order.cost,
                  outConnectName: this.order.outConnectName,
                  outConnectPhone: this.order.outConnectPhone,
                  outStartTime: this.order.outStartTime,
                  outEndTime: this.order.outEndTime,
                  remark: this.order.remark
                }
              })
              .then(response => {
                this.dialogFormVisible = false
                this.$message({
                  message: '新增成功',
                  duration: 1000
                })
                this.listProductItem()
              })
          }
        }
      })
    },
    restData() {
      this.dialogFormVisible = false
      this.dialogFormValue = ''
    },
    selected(val) {
      Object.assign(this.searchInfo, val)
      this.page = 1
      this.listProductItem()
    },
    add() {
      this.dialogFormVisible = true
      this.readonlyInput = false
      this.dialogFormValue = '新增派单'
    },
    seeDeleteItem(val) {
      this.dialogFormVisible = true
      this.dialogFormValue = '查看派单'
      this.readonlyInput = true
      this.order = {
        orderCode: val.orderCode,
        alignTime: val.alignTime,
        productId: val.productId ? val.productId : '',
        item: val.item,
        processName: val.processName,
        process: val.process,
        isAssist: val.isAssist,
        amount: val.amount,
        operaterName: val.operaterName,
        userId: val.userId,
        equipment: val.equipment,
        id: val.id,
        officeUserName: val.productItemAssist
          ? val.productItemAssist.officeUserName
          : '',
        cost: val.productItemAssist ? val.productItemAssist.cost : '',
        outConnectName: val.productItemAssist
          ? val.productItemAssist.outConnectName
          : '',
        outStartTime: val.productItemAssist
          ? val.productItemAssist.outStartTime
          : '',
        outEndTime: val.productItemAssist
          ? val.productItemAssist.outEndTime
          : '',
        remark: val.productItemAssist ? val.productItemAssist.remark : ''
      }
    },
    seeOrder(val) {}
    // upload(val) {
    //   this.dialogFormVisible = true;
    //   this.dialogFormValue = "修改派单";
    //   this.readonlyInput = false
    //   debugger
    //   this.order = {
    //     productId: val.productId,
    //     item: val.item,
    //     processName: val.processName,
    //     isAssist: val.isAssist,
    //     amount: val.amount,
    //     operaterName:val.operaterName,
    //     equipment: val.equipment,
    //     id:val.id,
    //     officeUserName:val.productItemAssist.officeUserName,
    //     outConnectName:val.productItemAssist.outConnectName,
    //     outConnectPhone:val.productItemAssist.outConnectPhone,
    // cost: val.productItemAssist ? val.productItemAssist.cost : '',
    //     outStartTime:val.productItemAssist.outStartTime,
    //     outEndTime:val.productItemAssist.outEndTime,
    //     remark:val.productItemAssist.remark,
    //   };
    // },
  }
}
</script>
<style>
.el-table .warning-row {
  background: #ff02027a;
}
</style>
